package com.zhangyu.shadow.core.net.rx;

import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.zhangyu.shadow.core.net.HttpMethod;
import com.zhangyu.shadow.core.net.RestCreator;
import com.zhangyu.shadow.core.net.callback.IError;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.ui.loader.LoaderStyle;
import com.zhangyu.shadow.core.ui.loader.ShadowLoader;

import java.io.File;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * Created by zhangyu on 2017/10/19.
 */

public class RxRestClient {
    public static final String SUCCESS_CODE = "200";
    private final String URL;
    private final Map<String, Object> PARAMS;
    private final RequestBody BODY;
    private final LoaderStyle LOADER_STYLE;
    private final Context CONTEXT;
    private final File FILE;
    private final ISuccess SUCCESS;
    private final IError ERROR;


    RxRestClient(String url,
                 Map<String, Object> params,
                 RequestBody body,
                 LoaderStyle loaderStyle,
                 Context context,
                 File file, ISuccess success, IError error) {
        URL = url;
        PARAMS = params;
        BODY = body;
        LOADER_STYLE = loaderStyle;
        CONTEXT = context;
        FILE = file;
        SUCCESS = success;
        ERROR = error;
    }

    public static RxRestClintBuilder builder() {
        return new RxRestClintBuilder();
    }

    private Observable<String> request(HttpMethod method) {
        final RxRestService service = RestCreator.getRxResetService();

        Observable<String> observable = null;
        if (LOADER_STYLE != null && CONTEXT != null) {
            ShadowLoader.showLoading(CONTEXT, LOADER_STYLE);
        }
        switch (method) {
            case GET:
                observable = service.get(URL, PARAMS);
                break;
            case POST:
                observable = service.post(URL, PARAMS);
                break;
            case POST_RAW:
                observable = service.postRaw(URL, BODY);
                break;
            case PUT:
                observable = service.put(URL, PARAMS);
                break;
            case PUT_RAW:
                observable = service.putRaw(URL, BODY);
                break;
            case DELETE:
                observable = service.delete(URL, PARAMS);
                break;
            case UPLOAD:
                final RequestBody requestBody = RequestBody.
                        create(MediaType.parse(MultipartBody.FORM.toString()), FILE);
                final MultipartBody.Part body = MultipartBody.
                        Part.createFormData("file", FILE.getName(), requestBody);
                observable = RestCreator.getRxResetService().upload(URL, body);
                break;
            default:
                break;
        }
        return observable;
    }

    public final Disposable get() {
        return request(HttpMethod.GET)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(@NonNull final String response) throws Exception {
                        int length = response.length();
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        String ResultCode = jsonObject.getString("ResultCode");
                        String object = jsonObject.getString("Result");
                        if (SUCCESS_CODE.equals(ResultCode)) {
                            if (SUCCESS != null) {
                                SUCCESS.onSuccess(object);
                                ShadowLoader.stopLoading();
                            }
                        } else {
                            String ResultMsg = jsonObject.getString("ResultMsg");
                            if (ERROR != null) {
                                ERROR.onError(-1, ResultMsg);
                                ShadowLoader.stopLoading();
                            }
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        if (ERROR != null) {
                            String msg = throwable.getMessage();
                            ERROR.onError(1001, msg);
                            ShadowLoader.stopLoading();
                        }

                    }
                });
    }

    public final Observable<String> onlyGet() {
        return request(HttpMethod.GET)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    public final Disposable post() {
        return request(HttpMethod.POST)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(@NonNull final String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        String ResultCode = jsonObject.getString("ResultCode");
                        String object = jsonObject.getString("Result");
                        if (SUCCESS_CODE.equals(ResultCode)) {
                            if (SUCCESS != null) {
                                SUCCESS.onSuccess(object);
                                ShadowLoader.stopLoading();
                            }
                        } else {
                            String ResultMsg = jsonObject.getString("ResultMsg");
                            if (ERROR != null) {
                                ERROR.onError(-1, ResultMsg);
                                ShadowLoader.stopLoading();
                            }
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        if (ERROR != null) {
                            String msg = throwable.getMessage();
                            ERROR.onError(1001, msg);
                            ShadowLoader.stopLoading();
                        }

                    }
                });
    }

    public final Observable<String> put() {
        if (BODY == null) {
            return request(HttpMethod.PUT);
        } else {
            if (!PARAMS.isEmpty()) {
                throw new RuntimeException("params must be null!");
            }
            return request(HttpMethod.PUT_RAW);
        }
    }

    public final Observable<String> delete() {
        return request(HttpMethod.DELETE);
    }

    public final Observable<ResponseBody> download() {
        return RestCreator.getRxResetService()
                .download(URL, PARAMS);
    }
}
